﻿using System;
using Transformable_Engine_v2.Engine.Animation.PositionAnimation;
using Transformable_Engine_v2.Engine.Animation.Trajectory;
using Transformable_Engine_v2.Engine.Global;
using Transformable_Engine_v2.Engine.Helper;
using Transformable_Engine_v2.Engine.Transformable_Math.Geometry;

namespace Transformable_Engine_v2.Engine.Animation.RotationAnimation
{
    public class RotationAnimation : BaseAnimation
    {
        public IRotationAnimatable AffectedObject { private get; set; }
        private readonly ITrajectory _trajectory;

        private double _beginRotation;
        private double _currentRotation;
        private readonly double _endRotation;

        public override void Update(TimeSpan gameTime)
        {
            
        }

        public override void FixedStepUpdate(TimeSpan gameTime)
        {
            if(IsAlive() && IsStarted)
            {
                double percentage = _trajectory.GetPercentageProgression(DurationTimer.PercentageElapsed);
                double nextRotation = (_endRotation - _beginRotation) * percentage + _beginRotation;
                AffectedObject.AddToRotation(nextRotation - _currentRotation);
                _currentRotation = nextRotation;
            }

            base.FixedStepUpdate(gameTime);
        }

        protected override void DelayEnd()
        {
            _beginRotation = AffectedObject.GetRotation();

            _currentRotation = _beginRotation;

            Log.LogDebug(this.ToString());

            base.DelayEnd();
        }

        public override string ToString()
        {
            return string.Format("Rotation from {0} to {1}", _beginRotation, _endRotation);
        }

        protected override void DurationEnd()
        {
            if (!IsLooping)
            {
                AffectedObject.AddToRotation(_endRotation - _currentRotation);
                _currentRotation = _endRotation;
            }
            base.DurationEnd();
        }

        public RotationAnimation(ITrajectory trajectory, double targetRotation,
                                    double duration, bool isLooping, double delay, bool autoStart = true)
            : base(duration, isLooping, delay, autoStart)
        {
            _trajectory = trajectory;

            _endRotation = targetRotation;
        }

        public override void Die()
        {
            AffectedObject = null;
            base.Die();
        }

    }
}